<script>
import PageShowMixin from "../mixins/PageShowMixin.js";
import simpleElementResizeDetector from "../utils/simple-element-resize-detector.js";

export default {
  name: "PageContent",
  mixins: [PageShowMixin],
  emits: ['scrollTop','sizeListen'],
  props: {
    isComponent: {
      type: Boolean,
      default: false,
    },
    showGoTop: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      scrollTop: 0,
      removeFunc: null,
    }
  },
  mounted() {
    this.removeFunc = simpleElementResizeDetector(this.$refs.sizeListen,this.sizeListenCall)
  },
  beforeDestroy() {
    if(this.removeFunc) {
      this.removeFunc()
    }
  },
  methods: {
    sizeListenCall(el, oldHeight, oldWidth) {
      this.$emit('sizeListen', oldHeight, oldWidth)
    },
    windowPageShow(ev) {
      if(ev.persisted){
        // 这里是需要个性化的
        if(!this.isComponent && this.$refs.pageContentRef) {
          this.$refs.pageContentRef.scrollTop = this.scrollTop
        }
      }
    },
    scrollFun(e) {
      this.scrollTop = e.target.scrollTop
      this.$emit('scrollTop',this.scrollTop)
    },
    gpTop(){
      this.$refs.pageContentRef.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
  }
}
</script>

<template>
  <div
      v-if="isComponent"
      ref="sizeListen"
      class="sizeListenClass"
  >
    <slot></slot>
  </div>
  <div
      class="pageContent"
      ref="pageContentRef"
      v-else
      @scroll="scrollFun"
  >
    <div class="goTop" @click.stop="gpTop" v-if="scrollTop>100 && showGoTop">
      <el-icon><CaretTop /></el-icon>
    </div>
    <div ref="sizeListen" class="sizeListenClass">
      <slot></slot>
    </div>
  </div>
</template>

<style scoped lang="scss">
.pageContent{
  height: 100vh;
  width: 100vw;
  overflow-x: hidden;
  overflow-y: auto;
  position: relative;
}
.sizeListenClass{
  width: auto !important;
  height: auto !important;
  margin: 0 !important;
  padding: 0 !important;
}

.goTop{
  position: fixed;
  bottom: 50%;
  right: 0;
  font-size: 24px;
  padding: 2px;
  background-color: #1989fa;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 4;
  .el-icon{
    font-weight: 600;
  }
}
</style>
